package com.example.springboottest.util;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.Resource;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aspose.words.*;
import com.aspose.words.net.System.Data.DataRow;
import com.aspose.words.net.System.Data.DataTable;

import java.lang.reflect.Field;
import java.util.List;

public class AsposeWordUtils {

    /**
     * 获取aspose 授权
     * @throws Exception
     */
    public static void setUnlimitedLicense() throws Exception {

        Resource resource = new ClassPathResource("lic/Aspose.Words.lic");
        License asposeLic = new License();
        asposeLic.setLicense(resource.getStream());
    }

    /**
     * 根据 DataTable 生成表格
     * @param doc
     * @param builder
     * @param dataList
     * @param declaredFields
     * @param tableName
     * @throws Exception
     */
    public static void createDataTable(Document doc, DocumentBuilder builder, List dataList,
                                       Field[] declaredFields, String tableName) throws Exception {
        DataTable dataTable = new DataTable(tableName);
        for (int i = 0; i < declaredFields.length; i++) {
            dataTable.getColumns().add(declaredFields[i].getName());
        }

        for (int i = 0; i < dataList.size(); i++) {
            JSONObject data = JSONUtil.parseObj(dataList.get(i));
            DataRow dataRow = dataTable.newRow();
            for (int j = 0; j < declaredFields.length; j++) {
                if("seq".equals(declaredFields[j].getName())){
                    dataRow.set(j,(i+1));
                    continue;
                }
                if(data.containsKey(declaredFields[j].getName())){
                    dataRow.set(j,data.get(declaredFields[j].getName()) ==null ? "" : data.get(declaredFields[j].getName()));
                }else{
                    dataRow.set(j,"");
                }
            }
            dataTable.getRows().add(dataRow);
        }

        doc.getMailMerge().executeWithRegions(dataTable);
    }


    /**
     *   输出标题信息
     * @param headerName
     * @param outlineLevel
     * @param builder
     * @param doc
     * @throws Exception
     */
    public static  void createHeaderText(String headerName,int outlineLevel,DocumentBuilder builder,Document doc) throws Exception {
        builder.moveToDocumentEnd();
        builder.getParagraphFormat().clearFormatting();
        ParagraphFormat paragraphFormat = builder.getParagraphFormat();
        paragraphFormat.setOutlineLevel(outlineLevel);
        Style heading = doc.getStyles().get("标题 "+outlineLevel);
        if(heading == null ){
            heading = doc.getStyles().get("Heading "+outlineLevel);
        }
        paragraphFormat.setStyle(heading);
        builder.writeln(headerName);
        builder.getParagraphFormat().clearFormatting();
    }

    /**
     *  输出正文信息
     * @param bodyText
     * @param builder
     * @param doc
     * @throws Exception
     */
    public static void createBodyText(String bodyText,DocumentBuilder builder,Document doc) throws Exception {
        builder.moveToDocumentEnd();
        builder.getParagraphFormat().clearFormatting();
        ParagraphFormat paragraphFormat = builder.getParagraphFormat();
        paragraphFormat.setOutlineLevel(9);
        Style Normal = doc.getStyles().get("正文");
        if(Normal == null ){
            Normal = doc.getStyles().get("Normal");
        }
        paragraphFormat.setStyle(Normal);
        builder.writeln(bodyText);
        builder.getParagraphFormat().clearFormatting();
    }


    public static void createTableRow(String[] tableTitles, DocumentBuilder builder,Style style) throws Exception {
        builder.getRowFormat().setHeight(20);
        for (int i = 0; i < tableTitles.length; i++) {
            builder.insertCell();
            builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
            builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            builder.getParagraphFormat().setStyle(style);
            builder.write(tableTitles[i] ==null?"":tableTitles[i]);
        }
        builder.endRow();
    }


    /**
     *  清除样式
     * @param builder
     * @param doc
     * @throws Exception
     */
    public static void clearBodyStyle(DocumentBuilder builder,Document doc) throws Exception {
        builder.moveToDocumentEnd();
        builder.getParagraphFormat().clearFormatting();
        ParagraphFormat paragraphFormat = builder.getParagraphFormat();
        paragraphFormat.setOutlineLevel(9);
        Style Normal = doc.getStyles().get("正文");
        if(Normal == null ){
            Normal = doc.getStyles().get("Normal");
        }
        paragraphFormat.setStyle(Normal);
        builder.getParagraphFormat().clearFormatting();
    }


    public static int getPageNumber(Document doc) throws Exception {
        Document targetDoc=doc.deepClone(); //将doc 赋给新的对象
        targetDoc.getFirstSection().remove();
        return targetDoc.getPageCount();
    }



    public static  void createLoopTable(JSONArray datas, String tableName, String[] fieldNames, String[] mergeNames, Document doc, DocumentBuilder builder) throws Exception {
        DataTable dataTable = new DataTable(tableName);
        dataTable.getColumns().add("index");
        for (String mergeName: mergeNames) {
            dataTable.getColumns().add(mergeName);
        }

        for (int i = 1; i < datas.size()+1; i++) {
            JSONObject object = datas.getJSONObject(i-1);
            DataRow dataRow = dataTable.newRow();
            dataRow.set(0,i);

            for(int j = 1;j < fieldNames.length+1;j++){
                dataRow.set(j,object.getStr(fieldNames[j-1]));
            }
            dataTable.getRows().add(dataRow);
        }
        doc.getMailMerge().executeWithRegions(dataTable);
    }


    public static  void writerHtmlContent(DocumentBuilder builder,String mergeName,String htmlContent) throws Exception {

//        builder.moveToMergeField(mergeName);
//
//        builder.insertHtml(htmlContent);

        builder.moveToMergeField(mergeName,false,true);
        builder.insertHtml(htmlContent,true);

    }


    public static  String formatText(String text){
        text = text.replace("\n","");
        text =  text.replace("\t","");
        text =  text.replace("\r","");
        text =  text.replace("\0","");
        text = text.replace("\f","");
        return  text;
    }

}
